package com.fadadianqi.mall.admin.controller;

import com.fadadianqi.commons.JSONProvider;
import com.fadadianqi.logistics.admin.controller.form.AjaxResult;
import com.fadadianqi.mall.product.SpuIndexService;
import com.yeqiangwei.commons.util.ParamUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by aroot on 2/27/14.
 */
@Controller
public class SearchIndexBuilderController {

    private static final Log log = LogFactory.getLog(SearchIndexBuilderController.class);

    @RequestMapping(value = "/mall/adm/search/index", method = RequestMethod.GET)
    public String show(HttpServletRequest request) throws Exception {
        return "/mall/admin/search/index";
    }

    @RequestMapping(value = "/mall/ajax/adm/search/index", method = RequestMethod.POST)
    public ResponseEntity<String> ajaxIndex(HttpServletRequest request, ModelMap modelMap) throws Exception {

        String errMsg = null;
        Boolean succeed = Boolean.FALSE;
        Boolean rebuild = ParamUtils.getBoolean(request, "rebuild", Boolean.TRUE);
        try {
            if(rebuild.booleanValue()) {
                spuIndexService.rebuild();
            } else {
                spuIndexService.build();
            }
            succeed = Boolean.TRUE;
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.toString());
        }
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "text/html; charset=utf-8");
        AjaxResult rs = new AjaxResult(null, succeed, errMsg);
        return new ResponseEntity<String>(JSONProvider.toJSON(rs),
                responseHeaders, HttpStatus.OK);
    }

    @Autowired
    private SpuIndexService spuIndexService;
}
